package com.chixing.listener;

import com.chixing.service.CouponService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CouponService couponService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();

        if (expiredKey.equals("indexHotCar")) {
            log.info(expiredKey + "key失效----动作触发,开始执行");
        } else {
            log.info(expiredKey + "key失效----动作触发,开始执行");
            Integer couponId = Integer.valueOf(expiredKey);
            //让优惠券失效
            couponService.updateById2Lapse(couponId);
            System.out.println("该优惠券失效已完成");

        }
        redisTemplate.delete(expiredKey);//执行完逻辑代码--删除Key
    }
}
